package com.haierp.service.xiaohongshu.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.haierp.enums.OrderStatus;
import com.haierp.enums.PlatformType;
import com.haierp.mapper.ItemMapper;
import com.haierp.mapper.ItemSkuMapper;
import com.haierp.mapper.OuterItemMapper;
import com.haierp.mapper.OuterItemSkuMapper;
import com.haierp.mapper.OuterOrderDetailMapper;
import com.haierp.mapper.OuterOrderMapper;
import com.haierp.model.Inventory;
import com.haierp.model.Item;
import com.haierp.model.ItemSku;
import com.haierp.model.item.OuterItem;
import com.haierp.model.item.OuterItemSku;
import com.haierp.model.sale.OuterOrder;
import com.haierp.model.sale.OuterOrderDetail;
import com.haierp.service.IInventoryService;
import com.haierp.service.IItemService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.item.IOuterItemService;
import com.haierp.service.xiaohongshu.IXiaohongshuService;
import com.haierp.util.DateUtil;
import com.haierp.util.DimensionCodeUtil;
import com.haierp.vo.json.PicModel;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("xiaohongshuService")
public class XiaohongshuServiceImpl implements IXiaohongshuService {
	protected Logger logger = LogManager.getLogger(getClass());

	@Autowired
	private ISequenceUtilService sequenceUtilService;

	@Autowired
	private OuterOrderMapper outerOrderMapper;

	@Autowired
	private OuterOrderDetailMapper outerOrderDetailMapper;

	@Autowired
	OuterItemMapper outerItemMapper;

	@Autowired
	OuterItemSkuMapper outerItemSkuMapper;

	@Autowired
	ItemMapper itemMapper;

	@Autowired
	ItemSkuMapper itemSkuMapper;

	@Autowired
	private IInventoryService inventoryService;

	@Autowired
	private IItemSkuService itemSkuService;

	@Autowired
	private IOuterItemService outerItemService;

	@Autowired
	private IItemService itemService;

	/**
	 * 添加订单
	 */
	@Override
	public List<Long> xiaohongshuTradesAdd(String type) {
		//交易状态更新的结束时间,值为当前时间
		Date EndUpdate = new Date();
		//交易状态更新的开始时间,值为当前时间的1个小时前，因为定时任务设置为半个小时,这样每个订单会有2次抓取机会
		Date StartUpdate = DateUtil.getDateByCalculate(EndUpdate, Calendar.HOUR_OF_DAY, -1);

		return xiaohongshuTradesAdd(StartUpdate, EndUpdate, type);
	}

	@Override
	public List<Long> xiaohongshuTradesAdd(Date StartUpdate, Date endUpdate, String type) {
		List<Long> outOrderIdList = new ArrayList<Long>();
		Map<String,String> params = new HashMap<>();
		String path = "/ark/open_api/v0/packages";
		Integer page_no=1;
		Integer totalPage=1;
		while(totalPage >= page_no){
			Integer page_size=50;
			params.put("start_time",DimensionCodeUtil.getSecondTimestamp(StartUpdate).toString());
			params.put("end_time",DimensionCodeUtil.getSecondTimestamp(endUpdate).toString());
			params.put("status","waiting");
			params.put("page_no",page_no.toString());
			params.put("page_size",page_size.toString());
			page_no++;
			try {
				String string = DimensionCodeUtil.redBookHttpRequest(path, params,"GET",type);
				JSONObject jsonObject = JSONObject.fromObject(string);
				Object data = jsonObject.get("data");
				JSONObject fromObject = JSONObject.fromObject(data);
				totalPage = (Integer)fromObject.get("total_page");
					Object packageList = fromObject.get("package_list");
					JSONArray fromObject2 = JSONArray.fromObject(packageList);
					if(fromObject2.isEmpty()) {
						return outOrderIdList;
					}
					for (Object object3 : fromObject2) {
						JSONObject fromObject3 = JSONObject.fromObject(object3);
						String packageId = fromObject3.getString("package_id");
						String pathDetail = "/ark/open_api/v0/packages/" + packageId;
						String result = DimensionCodeUtil.redBookHttpRequest(pathDetail, new HashMap<String, String>(), "GET",type);
						JSONObject fromObject4 = JSONObject.fromObject(result);
						Boolean tf = fromObject4.getBoolean("success");
						if(!tf){
							for (int i = 0; i < 10; i++) {
								String pathDetailOne = "/ark/open_api/v0/packages/" + packageId;
								String resultOne = DimensionCodeUtil.redBookHttpRequest(pathDetailOne, new HashMap<String, String>(), "GET",type);
								JSONObject fromObject5 = JSONObject.fromObject(resultOne);
								tf = fromObject5.getBoolean("success");
								if(tf){
									break;
								}
							}
							if(!tf) {
								logger.error("小红书未拉到的订单详情packageId：" + packageId);
								continue;
							}
						}
						Object object = fromObject4.get("data");
						JSONObject param = JSONObject.fromObject(object);
						//如果小红书订单已存在，略过
						OuterOrder p = new OuterOrder();
						p.setTargetNo(packageId);
						if(outerOrderMapper.selectCount(p) > 0) {
							continue;
						}
						//如果小红书订单还不存在，继续
						OuterOrder outerOrder = new OuterOrder();
						if("SL".equals(type)) {
							outerOrder.setCompanyId(3L);//小红书如花合作公司
							outerOrder.setSalesName("superladies");
							outerOrder.setSalesId(36L);
							outerOrder.setPlatformType(PlatformType.XIAOHONGSHUBAG.getCode());		               
						} else {
							outerOrder.setCompanyId(2L);//小红书下单更改所属公司
							outerOrder.setSalesName("coolforkids");
							outerOrder.setSalesId(5L);
							outerOrder.setPlatformType(PlatformType.XIAOHONGSHU.getCode());	
						}
						SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Long payTimeTemp = param.getLong("pay_time")*1000;
						Long timeTemp = param.getLong("time")*1000;
						Long confirmTimeTemp = param.getLong("confirm_time")*1000;
						String payTimeTempsd = sdf.format(new Date(payTimeTemp));
						String timeTempsd = sdf.format(new Date(timeTemp));
						String confirmTimeTempsd = sdf.format(new Date(confirmTimeTemp));
						Date payTime = sdf.parse(payTimeTempsd);
						Date time = sdf.parse(timeTempsd);
						Date confirmTime = sdf.parse(confirmTimeTempsd);
						outerOrder.setOrderNo("P"+String.format("%0"+2+"d", 1)+String.format("%0"+4+"d", 4)+"D"+DateUtil.formatDate(payTime, DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainORDSequence());	//系统自动生成
						outerOrder.setOrderTime(payTime);					                                 //付款时间
						outerOrder.setStatus(OrderStatus.INIT.getCode());			                         //状态：新建
						outerOrder.setReceiver(param.getString("receiver_name"));			                 //收货人
						if("北京".equals(param.getString("province")) || "天津".equals(param.getString("province"))
							|| "上海".equals(param.getString("province")) || "重庆".equals(param.getString("province"))){
							outerOrder.setReceiverState(param.getString("province")+"市");		             //省
						} else {
							outerOrder.setReceiverState(param.getString("province"));
						}
						outerOrder.setReceiverCity(param.getString("city"));			                     //市
						outerOrder.setReceiverDistrict(param.getString("district"));	                     //区
						outerOrder.setAddressDetail(param.getString("receiver_address"));	                 //详细地址
						outerOrder.setTelephone(param.getString("receiver_phone"));			                 //联系电话
						outerOrder.setPostcode(null);				                                         //邮编
						outerOrder.setRemark(null);				                                             //买家购买附言
						outerOrder.setTargetNo(packageId);						                             //小红书平台交易编号
						outerOrder.setIdCard(null);                                                          //身份证
						outerOrder.setUserCreate("小红书定时任务");								                 //创建者
						outerOrder.setGmtCreate(time);					                                     //创建时间
						outerOrder.setGmtModify(confirmTime);				                                 //修改时间
						outerOrderMapper.insert(outerOrder);								                 //添加主订单

						outOrderIdList.add(outerOrder.getId());								                 //收集主订单ID

						List<OuterOrderDetail> outerOrderDetails = new ArrayList<OuterOrderDetail>();
						Object itemList = param.get("item_list");
						JSONArray itemdetailList = JSONArray.fromObject(itemList);
						for (Object itemdetailTemp : itemdetailList) {
							JSONObject itemdetail = JSONObject.fromObject(itemdetailTemp);
							OuterOrderDetail outerOrderDetail = new OuterOrderDetail();
							outerOrderDetail.setOuterOrderId(outerOrder.getId());			                 //主订单ID
							outerOrderDetail.setCompanyId(outerOrder.getCompanyId());                        // 订单所属公司
							String OuterSkucode = itemdetail.getString("skucode");
							OuterItemSku ois = new OuterItemSku();
							ois.setOuterSkuCode(OuterSkucode);
							OuterItemSku outerItemSku = outerItemSkuMapper.selectOne(ois);
							if(outerItemSku != null){
								outerOrderDetail.setSkuCode(outerItemSku.getSkuCode());		                 //sku编码
							}
							outerOrderDetail.setSalePrice(itemdetail.getDouble("pay_price"));	             //商品单价
							outerOrderDetail.setQuantity(itemdetail.getInt("qty"));	                         //购买数量
							outerOrderDetail.setOid(null);                                                   //商品交易明细编号
							outerOrderDetail.setGmtCreate(time);		                                     //创建时间
							outerOrderDetail.setGmtModify(confirmTime);		                                 //修改时间
							outerOrderDetails.add(outerOrderDetail);

							//如果有虚拟库存就扣减虚拟库存
							ItemSku tjItemSku = new ItemSku();
							tjItemSku.setSkuCode(outerItemSku.getSkuCode());
							ItemSku itemSku = itemSkuService.selectOne(tjItemSku);
							if(itemSku != null) {
								Inventory inventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
								if(inventory.getVirtualInv()>0) {
									int virtualInv = inventory.getVirtualInv() - outerOrderDetail.getQuantity();
									virtualInv = virtualInv>0 ? virtualInv : 0;
									//如果虚拟库存小于等于可售库存，虚拟库存清零
									virtualInv = virtualInv>inventory.getTotalAvailableInv() ? virtualInv : 0;

									//如果虚拟占用库存大于零，有赞下单不应该减少虚拟预扣
									/*if(inventory.getLockedVirtualInv() > 0) {
										int lockedVirtualInv = inventory.getLockedVirtualInv() - outerOrderDetail.getQuantity();
										lockedVirtualInv = lockedVirtualInv>0 ? lockedVirtualInv : 0;
										inventory.setLockedVirtualInv(lockedVirtualInv);
									}*/
									inventory.setCompanyId(itemSku.getCompanyId());                          //所属
									inventory.setVirtualInv(virtualInv);
									inventory.setGmtModify(new Date());
									inventoryService.updateSelectiveById(inventory);
								}
							}
						}
						outerOrderDetailMapper.insertBatch(outerOrderDetails);				                 //添加子订单
					}
			} catch (Exception e) {
				logger.error(e);
			}
		}
		if(outOrderIdList.size() > 0) {
			//把商品详情更新到主订单明细里面
			outerOrderDetailMapper.updateOuterOrderDetailByItemSku(outOrderIdList);
		}
		return outOrderIdList;
	}

	@Override
	public Set<String> querySpuId(String type) throws Exception {
		Set<String> spuIdSet = new HashSet<>();
		Integer pageNo = 0;
		while (true) {
			Map<String,String> map = new HashMap<>();
			pageNo++;
			map.put("page_no",pageNo.toString());
			String path = "/ark/open_api/v1/items/lite";
			String result = DimensionCodeUtil.redBookHttpRequest(path,map,"GET",type);
			JSONObject jsonObject = JSONObject.fromObject(result);
			Object dataString = jsonObject.get("data");
			JSONObject data = JSONObject.fromObject(dataString);
			JSONArray jsonArray = JSONArray.fromObject(data.get("hits"));
			if (jsonArray.size()==0) {
				break;
			}
			for (int i = 0; i < jsonArray.size(); i++) {
				Object o = jsonArray.get(i);
				JSONObject json = JSONObject.fromObject(o.toString());
				String spuId = json.get("spu_id").toString();
				spuIdSet.add(spuId);
				/*String itemName = json.getJSONObject("spu").get("name").toString();
				String shortName = json.getJSONObject("spu").get("short_name").toString();
				String brand = json.getJSONObject("spu").getJSONObject("brand").get("name").toString();
				String category = json.getJSONObject("spu").getJSONArray("categories").getJSONObject(0).get("name").toString();
				System.out.println(spuId+" "+itemName+" "+shortName+" "+brand+" "+category);*/
			}
		}
		return spuIdSet;
	}

	@Override
	public Set<String> querySpuIdByTime(String updateStart,String updateEnd,String type) throws Exception {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Long updateTimeFrom =sdf.parse(updateStart).getTime()/1000;
		Long updateTimeTo = sdf.parse(updateEnd).getTime()/1000;
		Set<String> spuIdSet = new HashSet<>();
		Integer pageNo = 0;
		while (true) {
			Map<String,String> map = new HashMap<>();
			pageNo++;
			map.put("page_no",pageNo.toString());
			map.put("update_time_from",updateTimeFrom.toString());
			map.put("update_time_to",updateTimeTo.toString());
			String path = "/ark/open_api/v1/items/lite";
			String result = DimensionCodeUtil.redBookHttpRequest(path,map,"GET",type);
			JSONObject jsonObject = JSONObject.fromObject(result);
			Object dataString = jsonObject.get("data");
			JSONObject data = JSONObject.fromObject(dataString);
			JSONArray jsonArray = JSONArray.fromObject(data.get("hits"));
			if (jsonArray.size()==0) {
				break;
			}
			for (int i = 0; i < jsonArray.size(); i++) {
				Object o = jsonArray.get(i);
				JSONObject json = JSONObject.fromObject(o.toString());
				String spuId = json.get("spu_id").toString();
				spuIdSet.add(spuId);
				/*String itemName = json.getJSONObject("spu").get("name").toString();
				String shortName = json.getJSONObject("spu").get("short_name").toString();
				String brand = json.getJSONObject("spu").getJSONObject("brand").get("name").toString();
				String category = json.getJSONObject("spu").getJSONArray("categories").getJSONObject(0).get("name").toString();
				System.out.println(spuId+" "+itemName+" "+shortName+" "+brand+" "+category);*/
			}
		}
		return spuIdSet;
	}

	@Override
	public void querySpu(Set<String> spuIdSet,String type) throws Exception {
		Set<String> spuFailedSet = addItem(spuIdSet,type);
		for (int i = 0; i < 10; i++) {
			if (spuFailedSet.size() > 0) {
				spuFailedSet = addItem(spuFailedSet,type);
			}
		}
		if (spuFailedSet.size() > 0) {
			logger.error("未拉取的spu集合为: "+ spuFailedSet.toString());
		}
	}

	private Set<String> addItem(Set<String> spuIdSet,String type) throws Exception {
		Set<String> spuFailed = new HashSet<>();
		for (String s: spuIdSet) {
			try {
				EntityWrapper<OuterItem> entityWrapper = new EntityWrapper<>();
				entityWrapper.where("outer_alias = {0}", s);
				OuterItem selOuterItem = outerItemService.selectOne(entityWrapper);
				String path = "/ark/open_api/v1/spu/" + s;
				String result = DimensionCodeUtil.redBookHttpRequest(path, new HashMap<>(), "GET",type);
				JSONObject spus = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spus").getJSONObject(0);
				String itemName = spus.getString("name");
				String itemEnName = spus.getString("ename");
				String brand = spus.getJSONObject("brand").getString("name");
				String category = spus.getJSONArray("categories").getJSONObject(0).getString("name");
				String shortName = spus.getString("short_name");
				Map<String, String> spvsMap = new HashMap<>();
				Map<String, String> splsMap = new HashMap<>();
				Map<String, Double> weightMap = new HashMap<>();
				Map<String, List<String>> picMap = new HashMap<>();
				JSONArray spvs = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spvs");
				JSONArray spls = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spls");
				JSONArray items = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("items");

				JSONArray splItems = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spl_items");
				for (int i = 0; i < spvs.size(); i++) {
					JSONObject jsonObject = spvs.getJSONObject(i);
					String spvId = jsonObject.getString("id");
					Double weight = jsonObject.getDouble("gross_weight");
					weightMap.put(spvId, weight);
					JSONArray non_desc_variants = jsonObject.getJSONArray("non_desc_variants");
					StringBuffer sizeString = new StringBuffer();
					for (int j = 0; j < non_desc_variants.size(); j++) {
						String size = non_desc_variants.getJSONObject(j).getString("value");
						sizeString.append(size + " ");
					}
					spvsMap.put(spvId, sizeString.toString());
				}
				for (int i = 0; i < spls.size(); i++) {
					JSONObject jsonObject = spls.getJSONObject(i);
					String splId = jsonObject.getString("id");
					JSONArray non_desc_variants = jsonObject.getJSONArray("variants");
					StringBuffer sizeString = new StringBuffer();
					for (int j = 0; j < non_desc_variants.size(); j++) {
						String size = non_desc_variants.getJSONObject(j).getString("value");
						sizeString.append(size + " ");
					}
					splsMap.put(splId, sizeString.toString());
				}
				for (int i = 0; i < splItems.size(); i++) {
					JSONObject jsonObject = splItems.getJSONObject(i);
					String splId = jsonObject.getString("spl_id");
					if (!"null".equals(jsonObject.getString("images"))) {
						JSONArray images = jsonObject.getJSONArray("images");
						List<String> picList = new ArrayList<>();
						for (int j = 0; j < images.size(); j++) {
							String link = images.getJSONObject(j).getString("link");
							picList.add(link);
						}
						picMap.put(splId, picList);
					}
				}
				Item item = new Item();
				item.setBrand(brand);
				item.setCategoryName(category);
				if("SL".equals(type)) {
				item.setCompanyId(3L);
				item.setUserCreate("SL");
				} else {
				item.setCompanyId(2L);
				item.setUserCreate("xiaohongshu");
				}
				item.setName(itemName);
				item.setItemCode("I" + "0000000" + "Q" + sequenceUtilService.gainItemSequence());
				item.setIsNew(0);
				item.setSaleType(0);
				item.setItemShort(shortName);
				item.setEnName(itemEnName);
				item.setLogisticType(0);
				item.setCountry(1);
				item.setCurrency(1);
				item.setIsSale(1);
				item.setWxisSale(1);
				item.setStatus(1);
				item.setGmtModify(new Date());
				item.setGmtCreate(new Date());
				List<ItemSku> itemSkus = new ArrayList<>();
				int k = 0;
				Double minPrice = null;
				Double maxPrice = null;
				int status = 2;
				for (int i = 0; i < items.size(); i++) {
					ItemSku itemSku = new ItemSku();
					JSONObject jsonObject = items.getJSONObject(i);
					Double price = jsonObject.getDouble("price");
					if (minPrice == null) {
						minPrice = price;
						maxPrice = price;
					} else {
						if (minPrice > price) minPrice = price;
						if (maxPrice < price) maxPrice = price;
					}
					String upc = jsonObject.getString("barcode");
					Integer inventory = jsonObject.getInt("stock");
					String outerAlias = jsonObject.getString("id");
					String spv = spvsMap.get(jsonObject.getString("spv_id"));
					String spl = splsMap.get(jsonObject.getString("spl_id"));
					Double weightSku = weightMap.get(jsonObject.getString("spv_id"));
					List<String> pics = picMap.get(jsonObject.getString("spl_id"));
					String xhsSkuCode = jsonObject.getString("skucode");
					String statusStr = jsonObject.getString("buyable");
					if ("true".equals(statusStr)) {
						status = 1;
					}
					if("SL".equals(type)) {
						itemSku.setCompanyId(3L);
						itemSku.setUserCreate("SL");// CFK 后台商品
					} else {
						itemSku.setCompanyId(2L);
						itemSku.setUserCreate("xiaohongshu");// CFK 后台商品
					}
					itemSku.setSalePrice(price);
					itemSku.setSkuCode("S" + item.getItemCode().substring(1) + String.format("%0" + 4 + "d", ++k));
					itemSku.setSkuStatus(0);
					itemSku.setVirtualInv(inventory);
					itemSku.setColor(spl);
					itemSku.setScale(spv);
					itemSku.setUpc(upc);
					if(weightSku != null) {
					    itemSku.setWeight(weightSku/453.5);//小红书后台sku以克为单位
					} else {
						itemSku.setWeight(1.76);
					}
					itemSku.setXhsSkuCode(xhsSkuCode);
					itemSku.setOuterAlias(outerAlias);
					PicModel.PicList picList = new PicModel.PicList();
					List<PicModel.PicList> picLists = new ArrayList<>();
					picList.setType("image/jpeg");
					picList.setUid("i_0");
					if (pics != null) {
						picList.setUrl(pics.get(0));
					}
					picLists.add(picList);
					Map<String, List<PicModel.PicList>> pic = new HashMap<>();
					pic.put("picList", picLists);
					itemSku.setSkuPic(JSONObject.fromObject(pic).toString());
					if (i == 0) {
						List<PicModel.PicList> lists = new ArrayList<>();
						int u = 0;
						if (pics != null) {
							for (String picString : pics) {
								PicModel.PicList p = new PicModel.PicList();
								p.setType("image/jpeg");
								p.setUid("i_" + (u++));
								p.setUrl(picString);
								lists.add(p);
							}
						}
						PicModel picModel = new PicModel();
						picModel.setMainPicNum("1");
						picModel.setPicList(lists);
						item.setMainPic(JSONObject.fromObject(picModel).toString());
						if(weightSku != null) {
							item.setWeight(weightSku/453.5);//小红书后台sku以克为单位
						} else {
							item.setWeight(1.76);
						}
					}
					itemSku.setGmtCreate(new Date());
					itemSku.setGmtModify(new Date());
					itemSkus.add(itemSku);

				}
				if (minPrice.equals(maxPrice)) {
					item.setPriceRange(maxPrice.toString());
				} else {
					item.setPriceRange(minPrice.toString() + "-" + maxPrice.toString());
				}
				item.setStatus(status);
				item.setItemSkus(itemSkus);
				//itemService.addItem(item);
				if (selOuterItem == null) {
					itemService.insertSelective(item);
				} else {
					Item selItem = itemService.selectById(selOuterItem.getItemId());
					item.setId(selItem.getId());
					item.setItemCode(selItem.getItemCode());
					item.setGmtModify(new Date());
					itemService.updateSelectiveById(item);
				}
				OuterItem outerItem = new OuterItem();
				outerItem.setItemId(item.getId());
				if("SL".equals(type)) {
					outerItem.setPlatformType(3);
				} else {
					outerItem.setPlatformType(2);
				}
				outerItem.setOuterAlias(s);
				if (selOuterItem == null) {
					outerItemService.insertSelective(outerItem);
				}
				List<ItemSku> itemSkuList = item.getItemSkus();
				if (itemSkuList != null && !itemSkuList.isEmpty()) {
					Iterator<ItemSku> it = itemSkuList.iterator();
					List<OuterItemSku> outerItemSkus = new ArrayList<>();
					while (it.hasNext()) {
						ItemSku itemSku = it.next();
						OuterItemSku tjOuterItemSku = new OuterItemSku();
						tjOuterItemSku.setOuterAlias(itemSku.getOuterAlias());
						OuterItemSku selOuterItemSku = outerItemSkuMapper.selectOne(tjOuterItemSku);
						itemSku.setItemCode(item.getItemCode());
						itemSku.setItemName(item.getName());
						itemSku.setItemId(item.getId());
						itemSku.setCategoryId(item.getCategoryId());
						itemSku.setCategoryName(item.getCategoryName());
						itemSku.setBrand(item.getBrand());
						if (selOuterItemSku == null) {
							itemSkuService.insertSelective(itemSku);
							OuterItemSku outerItemSku = new OuterItemSku();
							outerItemSku.setItemId(item.getId());
							outerItemSku.setSkuId(itemSku.getId());
							if("SL".equals(type)) {
								outerItemSku.setPlatformType(3);
							} else {
								outerItemSku.setPlatformType(2);
							}
							outerItemSku.setSkuCode(itemSku.getSkuCode());
							outerItemSku.setOuterItemId(outerItem.getItemId());
							outerItemSku.setOuterSkuCode(itemSku.getXhsSkuCode());
							outerItemSku.setOuterAlias(itemSku.getOuterAlias());
							outerItemSkus.add(outerItemSku);
						} else {
							itemSku.setId(selOuterItemSku.getSkuId());
							itemSku.setGmtCreate(null);
							itemSku.setSkuCode(null);
							itemSkuService.updateSelectiveById(itemSku);
							it.remove();
						}
					}
				/*for (ItemSku sku : itemSkuList) {
					OuterItemSku outerItemSku = new OuterItemSku();
					outerItemSku.setItemId(item.getId());
					outerItemSku.setSkuId(sku.getId());
					outerItemSku.setPlatformType(2);
					outerItemSku.setSkuCode(sku.getSkuCode());
					outerItemSku.setOuterItemId(outerItem.getItemId());
					outerItemSku.setOuterSkuCode(sku.getXhsSkuCode());
					outerItemSku.setOuterAlias(sku.getOuterAlias());
					outerItemSkus.add(outerItemSku);
					if (sku.getId() != null) {
					}
				}*/
					if (outerItemSkus.size() > 0) {
						outerItemSkuMapper.insertBatch(outerItemSkus);
						List<Inventory> inventoryList = itemSkuService.initInventory(itemSkuList);
						inventoryService.insertBatch(inventoryList);
					}
				}
			} catch (Exception e) {
				spuFailed.add(s);
				logger.error("未拉下来的商品spu: "+s);
			}
		}
		return spuFailed;
	}

	
	/**
	 * 同步库存
	 */
	@Override
	public void synXhsSkuInventory(Long itemId,Long skuId,String type) {
		//查询是否同步到小红书
		OuterItem outerItemQuery = new OuterItem();
		outerItemQuery.setItemId(itemId);
		OuterItem outerItemDb = outerItemMapper.selectOne(outerItemQuery);
		if(outerItemDb==null){
			this.logger.info("没有找到对应的小红书商品，itemId:"+itemId);
		}
		else{
			//小红书下架上架中的商品不做判断
			if(outerItemDb.getStatus()!=null){
				OuterItemSku outerItemSkuQuery = new OuterItemSku();
				outerItemSkuQuery.setItemId(itemId);
				outerItemSkuQuery.setSkuId(skuId);
				OuterItemSku outerItemSkuDb = outerItemSkuMapper.selectOne(outerItemSkuQuery);
				if(outerItemSkuDb!=null&&outerItemSkuDb.getOuterSkuCode()!=null){
					Inventory inventory=inventoryService.queryInventoryBySkuId(itemId, skuId);
					//同步库存
					if(inventory!=null){
						String path = "/ark/open_api/v0/inventories/item/" + outerItemSkuDb.getOuterAlias();
						Map<String,String> params = new HashMap<>();
						params.put("qty", inventory.getSysInventory().toString());
						try {
							DimensionCodeUtil.redBookHttpRequest(path, params,"PUT",type);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}else{
						this.logger.info("没有找到库存信息，skuId:"+skuId);
					}
				}else{
					this.logger.info("没有找到对应的小红书skuCode，skuId:"+skuId);
				}
			}
		}
	}
	/**
	 * 获取物流公司映射
	 */
	@Override
	public Map<String, String>  xhsGetLogisticsCompany(String type) {
		Map<String, String> LogisticsExpressKey = new HashMap<String, String>();
		String pathDetail = "/ark/open_api/v0/express_companies" ;
		String result = null;
		try {
			result = DimensionCodeUtil.redBookHttpRequest(pathDetail,new HashMap<String,String>(), "GET", type);
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject jsonObject = JSONObject.fromObject(result);
		Object data = jsonObject.get("data");
		JSONArray dataList = JSONArray.fromObject(data);
		for (Object object : dataList) {
			JSONObject company = JSONObject.fromObject(object);
			LogisticsExpressKey.put(company.getString("express_company_name"), company.getString("express_company_code"));
		}
		return LogisticsExpressKey;
	}

	/*public static void main(String[] args) throws Exception {
		String pathDetail = "/ark/open_api/v0/express_companies" ;
		String result = DimensionCodeUtil.redBookHttpRequest(pathDetail,new HashMap<String,String>(), "GET");
		System.out.println("详情："+result);
		String path = "/ark/open_api/v0/inventories/item/" + "5ad1783e4628397ae2a85571";
		Map<String,String> params = new HashMap<>();
		params.put("qty", "20");
		String string = DimensionCodeUtil.redBookHttpRequest(path, params,"PUT");
		System.out.println(string.toString());
	}*/
	
	/*public static void main(String[] args) throws Exception {
		Set<String> spuIdSet = new HashSet<>();
		spuIdSet.add("5a531ddd462839682dd5d62f");
		spuIdSet.add("59a5218070e75226b3153a00");
		for (String s: spuIdSet) {
			String path = "/ark/open_api/v1/spu/"+s;
			String result = DimensionCodeUtil.redBookHttpRequest(path,new HashMap<>(),"GET");
			JSONObject spus = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spus").getJSONObject(0);
			String itemName = spus.getString("name");
			String itemEnName = spus.getString("ename");
			String brand = spus.getJSONObject("brand").getString("name");
			String category = spus.getJSONArray("categories").getJSONObject(0).getString("name");
			String shortName = spus.getString("short_name");
			Map<String,String> spvsMap = new HashMap<>();
			Map<String,String> splsMap = new HashMap<>();
			Map<String,List<String>> picMap = new HashMap<>();
			JSONArray spvs = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spvs");
			JSONArray spls = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spls");
			JSONArray items = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("items");
			JSONArray splItems = JSONObject.fromObject(result).getJSONObject("data").getJSONArray("spl_items");
			for (int i = 0; i < spvs.size(); i++) {
				JSONObject jsonObject = spvs.getJSONObject(i);
				String spvId = jsonObject.getString("id");
				JSONArray non_desc_variants = jsonObject.getJSONArray("non_desc_variants");
				StringBuffer sizeString = new StringBuffer();
				for (int j = 0; j < non_desc_variants.size() ; j++) {
					String size = non_desc_variants.getJSONObject(j).getString("value");
					sizeString.append(size+" ");
				}
				spvsMap.put(spvId,sizeString.toString());
			}
			for (int i = 0; i < spls.size(); i++) {
				JSONObject jsonObject = spls.getJSONObject(i);
				String splId = jsonObject.getString("id");
				JSONArray non_desc_variants = jsonObject.getJSONArray("variants");
				StringBuffer sizeString = new StringBuffer();
				for (int j = 0; j < non_desc_variants.size() ; j++) {
					String size = non_desc_variants.getJSONObject(j).getString("value");
					sizeString.append(size+" ");
				}
				splsMap.put(splId,sizeString.toString());
			}
			for (int i = 0; i < splItems.size(); i++) {
				JSONObject jsonObject = splItems.getJSONObject(i);
				String splId = jsonObject.getString("spl_id");
				JSONArray images = jsonObject.getJSONArray("images");
				List<String> picList = new ArrayList<>();
				for (int j = 0; j < images.size() ; j++) {
					String link = images.getJSONObject(j).getString("link");
					picList.add(link);
				}
				picMap.put(splId,picList);
			}
			Item item = new Item();
			item.setBrand(brand);
			item.setCategoryName(category);
			item.setCompanyId(2L);
			item.setName(itemName);
			int status = 2;
			for (int i = 0; i < items.size(); i++) {
				JSONObject jsonObject = items.getJSONObject(i);
				Double price = jsonObject.getDouble("price");
				String upc = jsonObject.getString("barcode");
				Integer inventory = jsonObject.getInt("stock");
				String spv = spvsMap.get(jsonObject.getString("spv_id"));
				String spl = splsMap.get(jsonObject.getString("spl_id"));
				List<String> pics = picMap.get(jsonObject.getString("spl_id"));
				String xhsSkuCode = jsonObject.getString("skucode");
				String statusStr = jsonObject.getString("buyable");
				if ("true".equals(statusStr)) {
					status = 1;
				}
				PicModel.PicList picList = new PicModel.PicList();
				picList.setType("image/jpeg");
				picList.setUid("i_0");
				picList.setUrl(pics.get(0));
				Map<String,PicModel.PicList> pic = new HashMap<>();
				pic.put("picList",picList);
				System.out.println(JSONObject.fromObject(pic).toString());
				if (i == 0) {
					List<PicModel.PicList> lists = new ArrayList<>();
					for (String picString: pics) {
						PicModel.PicList p = new PicModel.PicList();
						p.setType("image/jpeg");
						p.setUid("i_0");
						p.setUrl(pics.get(0));
						lists.add(p);
					}
					PicModel picModel = new PicModel();
					picModel.setMainPicNum("1");
					picModel.setPicList(lists);
					item.setMainPic(JSONObject.fromObject(picModel).toString());
					System.out.println("aaaaa"+JSONObject.fromObject(picModel).toString());
				}
			}
		}
	}*/
}
